package com.bookstore.service.impl;

import com.bookstore.dto.CategoryDTO;
import com.bookstore.entity.Category;
import com.bookstore.repository.CategoryRepository;
import com.bookstore.service.AdminCategoryService;
import org.springframework.stereotype.Service;

@Service
public class AdminCategoryServiceImpl extends BaseServiceImpl<Category, CategoryDTO, Long, CategoryRepository> implements AdminCategoryService {
    
    public AdminCategoryServiceImpl(CategoryRepository repository) {
        super(repository);
    }
    
    @Override
    protected CategoryDTO convertToDTO(Category category) {
        if (category == null) {
            return null;
        }
        
        CategoryDTO dto = new CategoryDTO();
        dto.setId(category.getId());
        dto.setCategoryName(category.getCategoryName());
        dto.setDescription(category.getDescription());
        dto.setDisplayOrder(category.getDisplayOrder());
        dto.setIcon(category.getIcon());
        
        if (category.getParent() != null) {
            dto.setParentId(category.getParent().getId());
            dto.setParentName(category.getParent().getCategoryName());
        }
        
        return dto;
    }
    
    @Override
    protected Category convertToEntity(CategoryDTO dto) {
        Category category = new Category();
        updateEntity(category, dto);
        return category;
    }
    
    @Override
    protected void updateEntity(Category category, CategoryDTO dto) {
        category.setCategoryName(dto.getCategoryName());
        category.setDescription(dto.getDescription());
        category.setDisplayOrder(dto.getDisplayOrder());
        category.setIcon(dto.getIcon());
        
        // 设置父分类
        if (dto.getParentId() != null) {
            Category parent = repository.findById(dto.getParentId())
                    .orElseThrow(() -> new RuntimeException("父分类不存在"));
            category.setParent(parent);
        } else {
            category.setParent(null);
        }
    }
}